package com.lt.flashcard.view;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.AddCoinHistory;
import com.lt.flashcard.model.entity.Orderdetail;
import com.lt.flashcard.model.service.EcommerceService;
import com.lt.flashcard.model.service.PaymentService;
import com.lt.flashcard.model.service.Repository;

/**
 * Process the payment result that returned from NganLuong gateway
 * @author ocsen
 *
 */
public class PaymentFinishCtrl extends SelectorComposer<Component> {
	
	public final static Logger log = Logger.getLogger(PaymentFinishCtrl.class);

	private static final long serialVersionUID = 1L;
	
	@Override
	public ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo) {
		
		String transaction_info = Executions.getCurrent().getParameter("transaction_info");
		String order_code = Executions.getCurrent().getParameter("order_code");
		String price = Executions.getCurrent().getParameter("price");
		String payment_id = Executions.getCurrent().getParameter("payment_id");
		String payment_type = Executions.getCurrent().getParameter("payment_type");
		String error_text = Executions.getCurrent().getParameter("error_text");
		String secure_code = Executions.getCurrent().getParameter("secure_code");
		String cancel_code = Executions.getCurrent().getParameter("cancel_code");
		
		if(log.isInfoEnabled()) {
			log.info("Access payment finish: " + Utility.getCurrentPage());
			log.info(String.format("Transaction_info: %s, order_code: %s, price: %s, payment_id: %s, payment_type: %s, error_text: %s, secure_code: %s, cancel_code: %s",
					transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code, cancel_code));
		}
		
		EcommerceService esrv = Repository.getInstance().getEcommerceService();
		
		if(!Utility.isEmptyString(cancel_code)) {
			//update the order
			if(cancel_code.startsWith("ADD:")) {
				String coinhistoryid = cancel_code.substring(4); //remove ADD:
				AddCoinHistory coinhistory = esrv.getAddCoinHistory(coinhistoryid);
				if(coinhistory == null) {
					log.error("Can't find add coin history for: " + cancel_code);
					return null;
				}
				esrv.updatePayment(coinhistory, AddCoinHistory.STATUS_CANCEL, "User cancels payment");
				Utility.rawRedirect("addcoin.zul", false);
			}
			else {
				Orderdetail order = esrv.getOrderdetail(cancel_code);
				if(order == null) {
                    return null;
                }
				esrv.updatePayment(order, Orderdetail.STATUS_CANCEL, "", "");
				Utility.rawRedirect(Utility.getContextPath(), false);
			}
		}
		else {
			boolean isAddcoin = order_code != null && order_code.startsWith("ADD:");
			
			PaymentService psrv = Repository.getInstance().getPaymentService();
			if(!psrv.checkPaymentReturnCode(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code)) {
				log.error("Invalid payment return code from: " + Utility.getIp());
				Utility.displayAccessDenied(false);
				return null;
			}
			
			if(isAddcoin) {
				String coinhistoryid = order_code.substring(4); //remove ADD:
				AddCoinHistory coinhistory = esrv.getAddCoinHistory(coinhistoryid);
				if(coinhistory == null) {
					log.error("Can't find add coin history for: " + order_code);
					return null;
				}
				esrv.updatePayment(coinhistory, AddCoinHistory.STATUS_COMPLETE, "");
				Utility.rawRedirect("addcoin.zul", false);
			}
			else {
				//update the order
				Orderdetail order = esrv.getOrderdetail(order_code);
				if(order == null) {
					log.error(String.format("Unknow order detail: %s", order_code));
					Utility.displayAccessDenied(false);
					return null;
				}
				
				if(StringUtils.isNotBlank(error_text)) {//incase of error
					esrv.updatePayment(order, Orderdetail.STATUS_PAYMENTERROR, error_text, "");
				}
				else {
					esrv.updatePayment(order, Orderdetail.STATUS_COMPLETE, "", payment_id);
				}
				
				Utility.rawRedirect("cart_finish.zul?id=" + order.getId(), false);
			}
		}
		
		return null;
	}
}
